﻿using Furion.CMS.Core;
using Furion.CMS.Core.EventSource;
using Furion.EventBus;
using Furion.TaskScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Web.Core
{
    public static class ServiceCollectionExtension
    {
        #region EventSourceService Settings
        /// <summary>
        /// 添加事件源服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="isAllowSynchronousIO">是否可以同步请求读取流数据</param>
        /// <returns></returns>
        public static IServiceCollection AddEventSourceService(this IServiceCollection services, bool isAllowSynchronousIO = true)
        {
            // 配置可以同步请求读取流数据
            services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = isAllowSynchronousIO)
                .Configure<IISServerOptions>(x => x.AllowSynchronousIO = isAllowSynchronousIO);

            // 启用心跳
            // 每隔 10s 执行
            SpareTime.Do(1000 * 10, (timer, count) =>
            {
                // 触发事件
                var eventPublisher = App.GetService<IEventPublisher>();
                eventPublisher?.PublishAsync(new OnTriggerOuterEvent(OuterEventCategory.Heartbeat));
            });

            return services;
        } 
        #endregion
    }
}
